package com.ttx;

import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Created by ttx on 17-9-23.
 */
public class ImageDownloader implements Runnable{
    static int failNum = 0;
    private static int createDirFlag;

    //图片存储根目录
    private String rootSavePath;
    private List<List<String>> urls;

    public ImageDownloader(){ }

    public ImageDownloader(String rootSavePath) {
        this.setRootSavePath(rootSavePath);
    }

    public ImageDownloader(String rootSavePath, List<List<String>> urls) {
//        this.setDataFilePath("dataFilePath");
        this.setRootSavePath(rootSavePath);
//        this.adl = new ArticleDataLoader("/home/ailly/SeanLab/java_code/data/test/split_file00");
//        adl.loadArticles();
        this.urls = urls;
    }


    public String getMD5(String name){
        String code = null;
        try {
            MessageDigest md  = MessageDigest.getInstance("MD5");
            //byte[] cipherData = md.digest(name.getBytes());
            md.update(name.getBytes());
            code = new BigInteger(1, md.digest()).toString(16);
            //code = cipherData.toString();
        } catch (NoSuchAlgorithmException e) {
            System.out.println("错误：MD5摘要生成出错！");
            e.printStackTrace();
        }
        return code;
    }

    //设置图片存储根目录
    public void setRootSavePath(String rootSavePath) {
        File tmp = new File(rootSavePath);
        if (!tmp.exists()) {
            System.out.println("错误：存储根目录不存在");
            System.exit(1);
        }
        if (rootSavePath.charAt(rootSavePath.length()-1) != '/') {
            rootSavePath = rootSavePath + "/";
        }
        this.rootSavePath = rootSavePath;
        //建立目录树
        if (createDirFlag != 1) {
            this.createSaveDirectory();
        }
    }

    //建立目录树
    private void createSaveDirectory(){
        String firstPrefix = "";
        String secondPrefix = "";
        File root = new File(rootSavePath);
        //检测根目录是否存在
        if (!root.exists()) {
            System.out.println("目录不存在");
            System.exit(1);
        }

        //创建目录树
        char[] vocab = "1234567890abcdefghijklmnopqrstuvwxyz".toCharArray();
        for (char first : vocab) {
            for (char second: vocab) {
                File tmp = new File(rootSavePath + firstPrefix + String.valueOf(first) + "/" + secondPrefix + String.valueOf(second));
                if (!tmp.exists()) {
                    tmp.mkdirs();
                }
            }
        }
        System.out.println("提示：存储目录树建立完毕！");
        createDirFlag = 1;
    }

    //取得图片保存路径
    public String getSavePath(String imgName){
        if (rootSavePath == null) {
            System.out.println("错误：未设置存储路径！");
            System.exit(1);
        }
        String newName = this.getMD5(imgName);
        String[] name = imgName.split("\\.");
        if(name.length == 1)return "";
        //文章名存储格式
        return rootSavePath + newName.charAt(0) + "/" + newName.charAt(1)+ "/" + newName + "." + imgName.split("\\.")[1];
        //return rootSavePath + newName.charAt(0) + "/" + newName.charAt(1)+ "/" + imgName;
    }


    public void saveImage(String imgURL) {
        String[] tmp =imgURL.split("/");
        String imgName = tmp[tmp.length - 1];
        saveImage(imgName, imgURL);
    }

    //保存图片
    public void saveImage(String imgName, String imgURL) {
        byte[] imageData = new byte[1024 * 1000];

        try {
            //url格式判断
            URL url = new URL(imgURL);
            HttpURLConnection conn = null;
            BufferedInputStream bis = null;

            String imgFileName = getSavePath(imgName);
            if(imgFileName == ""){
                failNum++;
                System.out.println("图片无后缀：" + imgName);
                return;
            }
            File imgFile = new File(imgFileName);


            if (!imgFile.exists() || imgFile.length() == 138 || imgFile.length() == 0) {
                if(imgFile.length() == 138 || imgFile.length() == 0){
                    imgFile.delete();
                }
                imgFile.createNewFile();

                try {
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(10 * 1000);
                    conn.setReadTimeout(50 * 1000);

                    bis = new BufferedInputStream(conn.getInputStream());
                } catch (Exception e) {
                    failNum++;
                    System.out.println("错误：图片下载失败！ " + imgURL);
                    System.out.println(e);
                    return;
                } finally {
                    // do something
                }

                DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imgFile)));

                int size = 0;
                while ( (size = bis.read(imageData) )!= -1) {
                    dos.write(imageData, 0 , size);
                }
                dos.flush();
                dos.close();
                bis.close();
                System.out.println("提示：成功保存图片！ " + getSavePath(imgName)  );

            } else {
                System.out.println("提示：图片已存在！" + getSavePath(imgName)  );
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        for(List<String> urlList:urls){
            for(String url:urlList){
                saveImage(url);
            }
        }
    }
}
